Classes

using System;

class Person
{
    // Properties
    public string Name { get; set; }
    public int Age { get; set; }

    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    // Method to display information
    public void DisplayInfo()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating an instance of the Person class
        Person person = new Person("John", 25);
        person.DisplayInfo();
    }
}

Properties

  • Properties provide controlled access to fields.

  • Equivalent to getter/setter methods.

class Player {
    public int Health { get; set; }
}

set  / get

  • Tutorial and examples of simplified Set/Get usage: ChristianHur video

  • Without access control for Set and Get:

public String car;
  • Simplified:

    public String car {get; private set;}
    
    • Using { set; get; }  creates an automatic property . This means the compiler automatically generates a private field to store the value, without needing to explicitly declare it in the class.

    • Equivalent to doing:

      private String _car; // Manually generated private field
      
      public String car
      {
          get { return _car; }
          set { _car = value; }
      }
      
  • Normal:

    public String car {
        get {
            return car;
        }
        private set {
            car = value;
        }
    }
    

Boxing / Unboxing

  • Boxing converts a value type into an object.

  • This allocates memory on the heap.

  • Boxing causes GC pressure, which is problematic in hot loops.

  • Boxing:

    int a = 5;
    object b = a; // boxing
    
  • Unboxing:

    int c = (int)b;